<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class SqlDebugMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 清空之前的查询日志
        DB::flushQueryLog();
        
        // 始终启用SQL查询记录
        DB::enableQueryLog();

        // 处理请求
        $response = $next($request);
        
        // 获取查询日志
        $queryLog = DB::getQueryLog();
        
        // 记录到日志文件
        Log::info('SQL查询日志', ['queries' => $queryLog, 'url' => $request->fullUrl()]);

        // 只在debug模式下添加SQL查询日志到响应
        if (config('app.debug')) {
            try {
                // 记录响应类型
                $responseType = get_class($response);
                Log::info('响应类型', ['type' => $responseType]);
                
                // 直接创建新的响应
                $statusCode = $response->getStatusCode();
                $headers = $response->headers->all();
                
                // 获取原始内容并解码
                $content = null;
                
                if ($response instanceof JsonResponse) {
                    // 如果是JsonResponse，直接获取数据
                    $content = $response->getData(true);
                    Log::info('JsonResponse内容', ['content' => json_encode($content)]);
                } elseif (method_exists($response, 'getContent')) {
                    // 尝试获取内容并解析JSON
                    $rawContent = $response->getContent();
                    Log::info('原始响应内容', ['content' => $rawContent]);
                    $content = json_decode($rawContent, true);
                } else {
                    // 如果是数组，直接使用
                    $content = $response;
                    Log::info('数组响应', ['content' => json_encode($content)]);
                }
                
                // 确保内容是数组
                if (!is_array($content)) {
                    Log::warning('响应内容不是数组，无法添加SQL查询日志');
                    return $response;
                }
                
                // 添加SQL查询日志
                $content['sql_queries'] = $queryLog;
                
                // 创建新的JsonResponse
                $newResponse = new JsonResponse($content, $statusCode);
                
                // 复制原始响应的头信息
                foreach ($headers as $key => $values) {
                    if ($key !== 'content-type') { // 跳过content-type，因为JsonResponse会设置
                        foreach ($values as $value) {
                            $newResponse->headers->set($key, $value);
                        }
                    }
                }
                
                Log::info('新响应内容', ['content' => json_encode($content)]);
                
                return $newResponse;
                
            } catch (\Exception $e) {
                Log::error('SQL调试中间件错误', [
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString(),
                    'line' => $e->getLine(),
                    'file' => $e->getFile()
                ]);
            }
        }
        
        return $response;
    }
}